﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BoAddonBiz_FreightForwarder.Cost.Bo;

namespace BoAddonBiz_FreightForwarder
{
    /// <summary>
    /// 费用方案
    /// </summary>
    public class B1Form_CreateCostList : SAPBoAddon.B1Form
    {
        private OrderLine line;
        protected override bool BeforeSaveCheckFormData()
        {
            return true;
        }

        protected override void FormEditModeChange(SAPBoAddon.frmItemEditMode frmEditMode)
        {

        }

        protected override void FormInfoSetting(SAPBoAddon.B1FormSetting FormSetting)
        {
            FormSetting.FormType = B1FormTypes.ado_AVA_FF_CreateCostList;
            FormSetting.FormFileName = "AVA_FF_CreateCostListForm.srf";
        }

        protected override void InitializeForm(SAPBoAddon.B1FormInitializePar InitPar)
        {

        }

        public B1Form_CreateCostList()
        {
            frm_ItemEvent += new SAPBoAddon.IB1FormEvents.B1ItemEventEventHandler(B1Form_CreateCostList_frm_ItemEvent);
        }

        void B1Form_CreateCostList_frm_ItemEvent(SAPBoAddon.B1AddonBase.B1ItemEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeAction)
            {
                if (pVal.ItemUID == "Grid" && pVal.Row >= 0 && pVal.EventType == SAPbouiCOM.BoEventTypes.et_CLICK)
                {
                    CurrentForm.Items.Item(pVal.ItemUID).Specific.Rows.SelectedRows.Add(pVal.Row);
                }
                if (pVal.ItemUID == "7" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)
                {
                    AddDataToParentForm(pVal.FormUID);
                }
            }
            else
            {
                if (pVal.ItemUID == "6" && (pVal.EventType == SAPbouiCOM.BoEventTypes.et_KEY_DOWN || pVal.ItemChanged))
                {
                    ListFind(pVal.FormUID);
                }
            }
        }
        /// <summary>
        /// 查找指定的数据
        /// </summary>
        /// <param name="FormUID"></param>
        private void ListFind(string FormUID)
        {
            SAPbouiCOM.Form oForm;
            string FieldName, FieldValue;

            oForm = SBOApp.Forms.Item(FormUID);
            FieldName = SAPBoAddon.B1Assistant.Item.GetValue(FormUID, "5").ToString();
            FieldValue = SAPBoAddon.B1Assistant.Item.GetValue(FormUID, "6").ToString();
            SAPBoAddon.B1Assistant.Grid.GridTableFindRow(FormUID, "Grid", "Table", FieldName, FieldValue);
        }
        /// <summary>
        /// 添加数据到父窗体
        /// </summary>
        /// <param name="FormUID"></param>
        private void AddDataToParentForm(string FormUID)
        {
            SAPbouiCOM.Form oForm;
            SAPbouiCOM.Form oParentForm;
            SAPbouiCOM.Form BNOForm;
            SAPbouiCOM.Grid oGrid;
            SAPbouiCOM.Matrix oMtx1;
            SAPbouiCOM.Matrix oMtx2;
            //SAPbouiCOM.DBDataSource dbds;
            SAPbobsCOM.Recordset ors;
            string BaseType = string.Empty;
            int DocEntry = -1;

            oForm = SBOApp.Forms.Item(FormUID);
            ors = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            oGrid = oForm.Items.Item("Grid").Specific;
            oParentForm = SBOApp.Forms.Item(oForm.DataSources.UserDataSources.Item("ParentUID").Value);
            BNOForm = SBOApp.Forms.Item(oParentForm.DataSources.UserDataSources.Item("ParentUID").Value);
            oMtx1 = oParentForm.Items.Item("mtx_0").Specific;
            oMtx2 = oParentForm.Items.Item("mtx_1").Specific;

            SAPbouiCOM.DataTable Dt_CCT1 = oParentForm.DataSources.DataTables.Item("DT_Rece");
            SAPbouiCOM.DataTable Dt_CCT2 = oParentForm.DataSources.DataTables.Item("DT_Pay");
            SAPbouiCOM.DBDataSource DBDS_OBNO = default(SAPbouiCOM.DBDataSource);

            int row = oGrid.Rows.SelectedRows.Item(0, SAPbouiCOM.BoOrderType.ot_RowOrder);//单据编号
            BaseType = oForm.DataSources.UserDataSources.Item("BaseType").Value;
            DocEntry = oGrid.DataTable.GetValue("DocEntry", row);

            string AVA_OQOT = "AVA_FF_OQOT";
            string AVA_QOT1 = "AVA_FF_QOT1";
            string AVA_QOT2 = "AVA_FF_QOT2";
            string AVA_OBNO = "@AVA_FF_OBNO";
            if (BNOForm.TypeEx == B1FormTypes.ado_AVA_SE_BusinessOperation)
            {
                AVA_OQOT = "AVA_SE_OQOT";
                AVA_QOT1 = "AVA_SE_QOT1";
                AVA_QOT2 = "AVA_SE_QOT2";
                AVA_OBNO = "@AVA_SE_OBNO";
            }
            if (BNOForm.TypeEx == B1FormTypes.ado_AVA_LN_BusinessOperation)
            {
                AVA_OQOT = "AVA_LN_OQOT";
                AVA_QOT1 = "AVA_LN_QOT1";
                AVA_QOT2 = "AVA_LN_QOT2";
                AVA_OBNO = "@AVA_LN_OBNO";
            }
            DBDS_OBNO = BNOForm.DataSources.DBDataSources.Item(AVA_OBNO);
            double LineQuantity = 1d;
            //oMtx.FlushToDataSource();//把数据刷新到Datasource
            if (BaseType == "S")//费用方案
            {
                ors.DoQuery(@"SELECT T1.DocEntry,T1.LineId,T1.U_ItemCode,T3.CodeBars U_CodeBars,T1.U_ItemName ,T2.U_Currency,T2.U_Price,T2.U_Unit
                            FROM [@AVA_FF_OFEE] T0
	                            INNER JOIN [@AVA_FF_FEE1] T1 ON T0.DocEntry = T1.DocEntry
	                            LEFT JOIN [@AVA_FF_FEE2] T2 ON T1.DocEntry = T2.DocEntry And T1.LineId = T2.U_LineID
                                LEFT JOIN OITM T3 ON T1.U_ItemCode = T3.ItemCode 
                            Where T0.Status = 'O' And T0.DocEntry = " + DocEntry);
            }
            else//报价
            {
                ors.DoQuery(String.Format(@"SELECT T1.DocEntry,T1.LineId,T1.U_ItemCode,T3.CodeBars U_CodeBars,T1.U_ItemName, T1.U_Currency,T1.U_Price,T2.U_Unit
                                FROM [@{0}] T0
	                                INNER JOIN [@{1}] T1 ON T0.DocEntry = T1.DocEntry
                                    INNER JOIN [@{2}] T2 ON T0.DocEntry = T2.DocEntry
                                    LEFT JOIN OITM T3 ON T1.U_ItemCode = T3.ItemCode 
                                Where T0.U_Status = 'R' And T0.DocEntry = {3}", AVA_OQOT, AVA_QOT1, AVA_QOT2, DocEntry));
            }
            string MatrixUID = string.Empty;
            string BoEntry = oParentForm.DataSources.UserDataSources.Item("BoEntry").ValueEx.Trim();
            string BoType = oParentForm.DataSources.UserDataSources.Item("BoType").ValueEx.Trim();
            string BoSerial = oParentForm.DataSources.UserDataSources.Item("BoSerial").ValueEx.Trim();
            string CardCode = oForm.DataSources.UserDataSources.Item("CardCode").ValueEx.Trim();
            string CardName = oForm.DataSources.UserDataSources.Item("CardName").ValueEx.Trim();
            if (ors.RecordCount > 0)
            {
                string InOut = oParentForm.DataSources.UserDataSources.Item("InOut").Value.Trim();//1/2
                for (int i = 0; i < ors.RecordCount; i++)
                {
                    if (InOut == "1")
                    {
                        MatrixUID = "mtx_0";
                        this.AddLine_MatrixBindDataTable(oParentForm, OrderType.SalesOrder, "DT_Rece", "mtx_0");
                        #region 订单实体对象赋值
                        line.BoType = BoType;
                        line.BoEntry = int.Parse(BoEntry);
                        line.BoSerialNum = BoSerial;

                        line.CardCode = CardCode;
                        line.CardName = CardName;
                        line.ItemCode = ors.Fields.Item("U_ItemCode").Value;
                        line.CodeBars = ors.Fields.Item("U_CodeBars").Value;
                        line.ItemName = ors.Fields.Item("U_ItemName").Value;
                        line.TaxRate = 0.00;
                        line.UnitMeasure = ors.Fields.Item("U_Unit").Value;/*added by WangPeng 2012年8月10日 17:33:14*/
                        this.SetQuantityByUnit(ref LineQuantity, line.UnitMeasure, DBDS_OBNO);/*by WangPeng 2012年8月24日 13:20:57*/
                        line.Quantity = LineQuantity;

                        line.Currency = ors.Fields.Item("U_Currency").Value;
                        line.Price = ors.Fields.Item("U_Price").Value;
                        decimal rate = Utils.GetRateByCurrency(ors.Fields.Item("U_Currency").Value, Utils.GetBopATDDate(BoEntry, BoType));
                        line.Rate = rate.ToString();
                        line.Enterman = Utils.GetCurrentUser().Operator;
                        line.EnterDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                        #endregion

                        #region 窗体显示赋值
                        Dt_CCT1.Rows.Offset = this.GetDataTableOffset(Dt_CCT1, this.GetMatrixLineId(oMtx1));
                        oMtx1.GetLineData(oMtx1.VisualRowCount);
                        Dt_CCT1.SetValue("CardCode", Dt_CCT1.Rows.Offset, line.CardCode);
                        Dt_CCT1.SetValue("CardName", Dt_CCT1.Rows.Offset, line.CardName);
                        Dt_CCT1.SetValue("ItemCode", Dt_CCT1.Rows.Offset, line.ItemCode);
                        Dt_CCT1.SetValue("CodeBars", Dt_CCT1.Rows.Offset, line.CodeBars);
                        Dt_CCT1.SetValue("ItemName", Dt_CCT1.Rows.Offset, line.ItemName);
                        Dt_CCT1.SetValue("Currency", Dt_CCT1.Rows.Offset, line.Currency);
                        Dt_CCT1.SetValue("Price", Dt_CCT1.Rows.Offset, line.Price);
                        Dt_CCT1.SetValue("Rate", Dt_CCT1.Rows.Offset, rate.ToString());
                        Dt_CCT1.SetValue("TaxRate", Dt_CCT1.Rows.Offset, line.TaxRate.ToString());
                        Dt_CCT1.SetValue("Quantity", Dt_CCT1.Rows.Offset, LineQuantity);
                        Dt_CCT1.SetValue("UnitMeasure", Dt_CCT1.Rows.Offset, line.UnitMeasure);

                        Dt_CCT1.SetValue("CostMoney", Dt_CCT1.Rows.Offset, line.Quantity * line.Price);//应收金额
                        Dt_CCT1.SetValue("AmountRMB", Dt_CCT1.Rows.Offset, line.Quantity * line.Price * Convert.ToDouble(rate));//折合RMB金额

                        #endregion
                        oMtx1.SetLineData(oMtx1.VisualRowCount);
                    }
                    else
                    {
                        MatrixUID = "mtx_1";
                        this.AddLine_MatrixBindDataTable(oParentForm, OrderType.Purchase, "DT_Pay", "mtx_1");
                        #region 订单实体对象赋值
                        line.BoType = BoType;
                        line.BoEntry = int.Parse(BoEntry);
                        line.BoSerialNum = BoSerial;
                        line.ItemCode = ors.Fields.Item("U_ItemCode").Value;
                        line.ItemName = ors.Fields.Item("U_ItemName").Value;
                        line.CodeBars = ors.Fields.Item("U_CodeBars").Value;
                        line.UnitMeasure = ors.Fields.Item("U_Unit").Value;/*added by WangPeng 2012年8月10日 17:41:22*/
                        this.SetQuantityByUnit(ref LineQuantity, line.UnitMeasure, DBDS_OBNO);/*by WangPeng 2012年8月24日 13:20:57*/
                        line.Quantity = LineQuantity;
                        line.Currency = ors.Fields.Item("U_Currency").Value;
                        line.Price = ors.Fields.Item("U_Price").Value;
                        decimal rate = Utils.GetRateByCurrency(ors.Fields.Item("U_Currency").Value, Utils.GetBopATDDate(BoEntry, BoType));
                        line.Rate = rate.ToString();
                        line.Enterman = Utils.GetCurrentUser().Operator;
                        line.EnterDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                        #endregion

                        #region 窗体显示赋值
                        Dt_CCT2.Rows.Offset = this.GetDataTableOffset(Dt_CCT2, this.GetMatrixLineId(oMtx2));
                        oMtx2.GetLineData(oMtx2.VisualRowCount);
                        Dt_CCT2.SetValue("ItemCode", Dt_CCT2.Rows.Offset, line.ItemCode);
                        Dt_CCT2.SetValue("CodeBars", Dt_CCT2.Rows.Offset, line.CodeBars.ToString());
                        Dt_CCT2.SetValue("ItemName", Dt_CCT2.Rows.Offset, line.ItemName.ToString());
                        Dt_CCT2.SetValue("Currency", Dt_CCT2.Rows.Offset, line.Currency);
                        Dt_CCT2.SetValue("Price", Dt_CCT2.Rows.Offset, line.Price);
                        Dt_CCT2.SetValue("Rate", Dt_CCT2.Rows.Offset, rate.ToString());
                        Dt_CCT2.SetValue("Quantity", Dt_CCT2.Rows.Offset, LineQuantity);
                        Dt_CCT2.SetValue("UnitMeasure", Dt_CCT2.Rows.Offset, line.UnitMeasure);

                        Dt_CCT2.SetValue("CostMoney", Dt_CCT2.Rows.Offset, line.Quantity * line.Price);//应收金额
                        Dt_CCT2.SetValue("AmountRMB", Dt_CCT2.Rows.Offset, line.Quantity * line.Price * Convert.ToDouble(rate));//折合RMB金额
                        #endregion
                        oMtx2.SetLineData(oMtx2.VisualRowCount);
                    }
                    ors.MoveNext();
                }
                B1Form_CreateCost.SumRMB(oParentForm);
                B1Form_CreateCost.CreditSumRMB(oParentForm);
                B1Form_CreateCost.DebitSumRMB(oParentForm);
                if (oParentForm.Mode == SAPbouiCOM.BoFormMode.fm_OK_MODE) oParentForm.Mode = SAPbouiCOM.BoFormMode.fm_UPDATE_MODE;

            }
            oForm.Close();
            //oMtx.LoadFromDataSource();//加载数据从Datasource
        }
        private object GetMatrixLineId(SAPbouiCOM.Matrix oMtx)
        {
            int LineId = 0;
            if (oMtx.VisualRowCount == 0)
            {
                LineId = 1;
            }
            else
            {
                LineId = Convert.ToInt32(SAPBoAddon.B1Assistant.Matrix.GetCellValue(oMtx, "col_f", oMtx.VisualRowCount));
            }
            return LineId;
        }

        private int GetDataTableOffset(SAPbouiCOM.DataTable dt_Use, object LineId)
        {
            int offset_Dt = 0;
            for (int i = 0; i < dt_Use.Rows.Count; i++)
            {
                if (dt_Use.GetValue("Index", i).ToString() == LineId.ToString())
                {
                    offset_Dt = i;
                }
            }
            return offset_Dt;
        }

        private void AddLine_MatrixBindDataTable(SAPbouiCOM.Form oParentForm, OrderType ordertyp, string Table, string MatrixUID, bool isFirst = false)
        {
            SAPbouiCOM.DataTable dt_Rece = oParentForm.DataSources.DataTables.Item(Table);
            SAPbouiCOM.Matrix oMtx = oParentForm.Items.Item(MatrixUID).Specific;

            line = B1Form_CreateCost.B1Order.Add(ordertyp);
            int LineId = 0;
            if (oMtx.RowCount > 0)
            {
                LineId = dt_Rece.GetValue("Index", dt_Rece.Rows.Count - 1);
                dt_Rece.Rows.Add();
            }
            if (dt_Rece.Rows.Count <= 0)
            {
                dt_Rece.Rows.Add();
            }
            dt_Rece.Rows.Offset = dt_Rece.Rows.Count - 1;
            dt_Rece.SetValue("Index", dt_Rece.Rows.Offset, LineId + 1);
            dt_Rece.SetValue("LineNum", dt_Rece.Rows.Offset, line.LineNum);
            dt_Rece.SetValue("DocEntry", dt_Rece.Rows.Offset, line.DocEntry);

            oMtx.AddRow();
            oMtx.SetLineData(oMtx.RowCount);
        }
        /// <summary>
        /// 根据计量单位设置数量
        /// </summary>
        /// <author>WangPeng</author>
        private void SetQuantityByUnit(ref double LineQuanitity, string Unit, SAPbouiCOM.DBDataSource DBDS_OBNO)
        {
            if (new string[] { "SHIPMENT" }.Contains<string>(Unit.ToUpper()))
            {
                LineQuanitity = 1d;
            }
            else if (Unit.ToUpper() == "KG")
            {
                LineQuanitity = Convert.ToDouble(DBDS_OBNO.GetValue("U_BillingWeight", DBDS_OBNO.Offset).Trim());/*获取业务单总计费重*/
            }
            else if (Unit.ToUpper() == "PCS")
            {
                LineQuanitity = Convert.ToDouble(DBDS_OBNO.GetValue("U_Quantity", DBDS_OBNO.Offset).Trim());/*获取业务单总件数*/
            }
            else if (Unit.ToUpper() == "CBM")
            {
                LineQuanitity = Convert.ToDouble(DBDS_OBNO.GetValue("U_Volume", DBDS_OBNO.Offset).Trim());/*获取业务单总体积CBM*/
            }
            else
            {
                LineQuanitity = 1;
            }
        }
    }
}
